/* eslint-disable array-callback-return */
/* eslint-disable react-hooks/rules-of-hooks */
import { Row, Col, Card, theme, Pagination } from "antd";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { BetaSchemaForm, ProFormSelect } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { getFetch } from "@/utils/doFetch";

function Mcard({
  actionRef,
  formRef,
  columns = [], //columns
  style, //style
  path, //接口地址
  extraparams, //额外参数
  pageSize, //修改默认pageSize
  pagination = true, //分页设置
  activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
  getDefaultSelected, //存在默认选中向上返回选中值
  dataSource,
  renderCardItem, //自定义卡片样式
  cardProps = {
    type: "default",
  }, // 卡片配置
  iscurrent = true,
  dataSourceFieldsChange,
  tablebordered = false,
  col = { xs: 24, sm: 12, md: 12, lg: 8, xl: 8, xxl: 6 },
}) {
  const {
    token: { colorBorder, colorBglight },
  } = theme.useToken();

  const [formvalues, setFormvalues] = useState({});
  const [total, setTotal] = useState(0);

  const [page, setPage] = useState(
    pagination
      ? {
          pageIndex: 1,
          pageSize: 10,
        }
      : null
  );

  const myactionRef = actionRef ?? useRef();
  const myformRef = formRef ?? useRef();

  const { data, loading, refresh } = useRequest(
    async () => {
      if (path) {
        const res = await getFetch({
          url: path,
          params: { ...formvalues, ...extraparams, ...(page ?? {}) },
        });
        setTotal(
          res?.data?.dataList?.length ?? parseInt(res?.data?.page?.total)
        );
        return res?.data?.dataList ?? res?.data?.page?.records;
      } else {
        return dataSource;
      }
    },
    {
      refreshDeps: [extraparams, formvalues, dataSource, page],
    }
  );

  const cardItem = useCallback(
    (item, i) => {
      let dom = null;
      switch (cardProps.type) {
        case "default":
          dom = (
            <Col
              {...col}
              key={i}
              style={{
                marginBottom: 12,
              }}
            >
              <div
                style={{
                  backgroundColor: colorBglight,
                  width: "100%",
                  height: "100%",
                  padding: 12,
                  borderRadius: 8,
                }}
              >
                {columns?.map((column, i) => {
                  return i === 0 ? (
                    <h3
                      key={i}
                      style={{ flex: 1, textAlign: "left" }}
                      className="oneline"
                    >
                      {column?.render?.(item[columns?.dataIndex], item) ??
                        item?.[column?.dataIndex]}
                    </h3>
                  ) : (
                    <div
                      key={i}
                      className="spread"
                      style={{ gap: 12, marginBottom: 6 }}
                    >
                      <span style={{ opacity: 0.5 }}>{column?.title}</span>
                      <span
                        style={{ flex: 1, textAlign: "right" }}
                        className="oneline"
                        title={item?.[column?.dataIndex]}
                      >
                        {column?.render?.(item[columns?.dataIndex], item) ??
                          (item?.[column?.dataIndex] ?? '-')}
                      </span>
                    </div>
                  );
                })}
              </div>
            </Col>
          );

          break;

        default:
          break;
      }
      return dom;
    },
    [cardProps]
  );

  useEffect(() => {
    myactionRef.current = {
      ...myactionRef.current??{},
      reload: refresh
    };
  }, [refresh]);

  return (
    <Row gutter={12}>
      <Col span={24} style={{ marginBottom: 12 }}>
        <BetaSchemaForm
          formRef={myformRef}
          layoutType={"LightFilter"}
          rowProps={{
            gutter: [16, 16],
          }}
          colProps={{
            span: 12,
          }}
          grid={false}
          onFinish={async (values) => {
            console.log(values);
          }}
          columns={columns?.map((it) => {
            const valueEnum = {};
            if (Array.isArray(it.options)) {
              it.options.map((cur) => {
                valueEnum[cur.value] = {
                  text: cur.label,
                  status: "Default",
                };
              });
            }

            const extravalueEnum =
              Object.keys(valueEnum)?.length > 0 ? { valueEnum } : {};

            return {
              ...it,
              ...extravalueEnum,
              hideInForm: it?.hideInSearch || it.search === false,
              valueType: it.searchValueType ? it.searchValueType : it.valueType,
              formItemProps: {
                ...it.formItemProps,
                rules: [],
              },
            };
          })}
          onValuesChange={(changedValues, values) => {
            setFormvalues(values);
          }}
          placement="bottomLeft"
        />
      </Col>
      {[...(data ?? [])]?.map?.((item, i) => {
        return renderCardItem?.(item, i) ?? cardItem(item, i);
      })}
      {pagination && (
        <Col span={24} style={{ marginTop: 12 }}>
          <Pagination
            size="small"
            total={total}
            showTotal={(total) => `共 ${total} 条`}
            pageSize={page.pageSize}
            current={page.pageIndex}
            showSizeChanger
            showQuickJumper
            onChange={(pageIndex, pageSize) => {
              setPage({ pageIndex: pageIndex, pageSize: pageSize });
            }}
          />
        </Col>
      )}
    </Row>
  );
}

export default Mcard;
